package org.bioversityinternational.mgbms.text;

import java.text.SimpleDateFormat;
import java.util.Random;

import org.bioversityinternational.mgbms.model.domain.Address;

public class Helper
{
    /**
     * RFC 2822 compliant
     * http://www.regular-expressions.info/email.html
     */
    private final static String EMAIL_VALIDATION_REGEX = "[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?";

	static final public SimpleDateFormat df = new SimpleDateFormat(TextConstants.get("defaultDateFormat"));

	public static final String nullToBlank(String s)
	{
		return nullToBlank(s, "");
	}
	
	public static final String nullToBlank(String s, String sToAppendIfNotNull)
	{
		return s == null || s.length() == 0 ? "" : (s + sToAppendIfNotNull);
	}
	
	public static final String compileAddress(Address a)
	{
		StringBuffer sb = new StringBuffer();
		sb.append(nullToBlank(a.getAddress1(), "\n"));
		sb.append(nullToBlank(a.getAddress2(), "\n"));
		sb.append(nullToBlank(a.getZipCode(), " " + nullToBlank(a.getCity(), ", ")));
		String sProvince = a.getProvince();
		if (sProvince != null && !sProvince.equals(a.getCity()))
			sb.append(nullToBlank(sProvince, ", "));
		sb.append(nullToBlank(a.getCountry().getLabel()));
		
		return sb.toString();
	}
	
    static public boolean isEmailValid(String sEmail)
    {
		return (nullToBlank(sEmail).matches(EMAIL_VALIDATION_REGEX));	
	}    

	static public String stripHTML (String sToStrip)
	{
		  String sStripped = sToStrip;
		  boolean finished = false;
		  while ( !finished ) {
		    int openSqrBracketPos = sStripped.indexOf( "<" );
		    int closeSqrBracketPos = sStripped.indexOf( ">", openSqrBracketPos );
		    if (( openSqrBracketPos != -1 ) && ( closeSqrBracketPos != -1 )) {
		      sStripped = sStripped.substring( 0, openSqrBracketPos ) +
		                 sStripped.substring( closeSqrBracketPos + 1 );
		    } else {
		      finished = true;
		    }
		  }
		  return sStripped;
	}
}
